package com.snoob.springboot.enterprise.controller;

import com.snoob.springboot.base.BaseException;
import com.snoob.springboot.enterprise.entity.EnterpriseEntity;
import com.snoob.springboot.enterprise.entity.EnterpriseUserEntity;
import com.snoob.springboot.enterprise.service.EnterpriseService;
import com.snoob.springboot.enterprise.service.EnterpriseUserService;
import com.snoob.springboot.enterprise.util.EnterpriseRegisterUtil;
import com.snoob.springboot.enums.SysStateEnum;
import com.snoob.springboot.pipleline.vo.EnterpriseRegisterVoReq;
import com.snoob.springboot.pipleline.vo.EnterpriseRegisterVoRes;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;

/**
 * @描述：企业注册
 * @作者：lixing_java@163.com
 * @时间：2022/5/14 16:16
 */
//@RestController
//@RequestMapping("enterpriseRegister")
@Component
public class EnterpriseRegisterController {
    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private EnterpriseUserService enterpriseUserService;

    /**
     * @描述 企业注册（第一步：创建企业；第二步：创建用户）
     */
    //@PostMapping("enterpriseRegister")
    public EnterpriseRegisterVoRes enterpriseRegister(@RequestBody EnterpriseRegisterVoReq dto) {
        // 校验参数
        EnterpriseRegisterUtil.checkRegisterParam(dto);

        // 创建企业
        EnterpriseEntity enterpriseEntity = new EnterpriseEntity();
        enterpriseEntity.setEnterpriseName(dto.getEnterpriseName());
        enterpriseEntity.setEnterpriseRemark(dto.getEnterpriseRemark());
        String enterpriseCode = enterpriseService.insertEnterprise(enterpriseEntity);
        if (null == enterpriseCode) {
            throw new BaseException("创建企业失败"); // 触发事务回滚
        }

        // 创建用户
        EnterpriseUserEntity enterpriseUserEntity = new EnterpriseUserEntity();
        enterpriseUserEntity.setEnterpriseCode(enterpriseCode);
        enterpriseUserEntity.setGrade(SysStateEnum.USER_GRADE_SUPER.getValue());
        enterpriseUserEntity.setUserAccount(dto.getUserPhone());
        enterpriseUserEntity.setUserName(dto.getUserName());
        enterpriseUserEntity.setUserPhone(dto.getUserPhone());
        String userAccount = enterpriseUserService.insertEnterpriseUser(enterpriseUserEntity);
        if (null == userAccount) {
            throw new BaseException("创建企业用户失败"); // 触发事务回滚
        }

        // 异步发送短信通知用户，短信内容：登陆地址、账号、密码

        //
        EnterpriseRegisterVoRes enterpriseRegisterVoRes = new EnterpriseRegisterVoRes();
        enterpriseRegisterVoRes.setEnterpriseCode(enterpriseUserEntity.getEnterpriseCode());
        enterpriseRegisterVoRes.setUserAccount(userAccount);
        return enterpriseRegisterVoRes;
    }
}
